package com.mai4j.practice.pdf;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Slf4j
public class PdfGenerator {

    /**
     * @param out  pdf输出流
     * @param html 页面
     * @throws PdfException PdfException
     */
    public static void createPdf(OutputStream out, String html) throws PdfException {
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)));
            ITextRenderer textRenderer = ITextRendererHelper.get();
            textRenderer.setDocument(doc, null);
            textRenderer.layout();
            textRenderer.createPDF(out);
        } catch (Exception e) {
            throw new PdfException("创建PDF错误！", e);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }
}
